package br.edu.sistemaacademico;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.text.Document;

import br.edu.sistemaacademico.Decorator.ConcretDecorator;
import br.edu.sistemaacademico.adapter.IMenuCadastro;
import br.edu.sistemaacademico.facade.DataFacade;
import br.edu.sistemaacademico.observer.Observavel;
import br.edu.sistemaacademico.observer.Observer;
import br.edu.sistemaacademico.observer.ValidaEspecial;
import br.edu.sistemaacademico.pojo.Classe;
import br.edu.sistemaacademico.pojo.Curso;
import br.edu.sistemaacademico.pojo.Disciplina;
import client.ClientCommand;


public class frmAtualizaCurso extends IMenuCadastro{

	 ConcretDecorator cc = null;
	    Curso curso = new Curso();
	    Disciplina disciplina;
	    Classe classe = new Classe();
	    public List<Object> campos = ClientCommand.getCampos("DisciplinaService");// new ArrayList<Object>();
	    private List<Object> valores = new ArrayList<Object>();
	    private List<Object> tamanho = new ArrayList<Object>();
	    public List<Object> camposClasse = new LinkedList<Object>();
	    private List<Object> valoresClasse = new ArrayList<Object>();
	    List<Disciplina> extra;
	    List<Classe> classes = new LinkedList<Classe>();
	    TabelaModelo tabModel;
	    TabelaModelo tabModelGrade;
	    int periodo = 0;
	    public frmAtualizaCurso(Curso curso) {
	        this.curso = curso;
	    	execute();
	    }
	    @SuppressWarnings("unchecked")
	    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
	    private void initComponents() {

	        jLabel1 = new javax.swing.JLabel();
	        jLabel2 = new javax.swing.JLabel();
	        jTextField1 = new javax.swing.JTextField();
	        jTextField2 = new javax.swing.JTextField();
	        jTabbedPane1 = new javax.swing.JTabbedPane();
	        jScrollPane2 = new javax.swing.JScrollPane();
	        jTable2 = new javax.swing.JTable();
	        jScrollPane1 = new javax.swing.JScrollPane();
	        jTable1 = new javax.swing.JTable();
	        jButton1 = new javax.swing.JButton();
	        jButton2 = new javax.swing.JButton();
	        jButton3 = new javax.swing.JButton();
	        jLabel3 = new javax.swing.JLabel();
	        jLabel4 = new javax.swing.JLabel();
	        jTextField3 = new javax.swing.JTextField();
	        jButton4 = new javax.swing.JButton();

	        setPreferredSize(new java.awt.Dimension(525, 357));

	        jLabel1.setText("Nome");
	        jLabel1.setName("jLabel1"); // NOI18N

	        jLabel2.setText("Regulamentado");
	        jLabel2.setName("jLabel2"); // NOI18N

	        jTextField1.setName("jTextField1"); // NOI18N

	        jTextField2.setName("jTextField2"); // NOI18N

	        jTabbedPane1.setName("jTabbedPane1"); // NOI18N
	        jTabbedPane1.setPreferredSize(new java.awt.Dimension(458, 300));

	        jScrollPane2.setName("jScrollPane2"); // NOI18N

	        jTable2.setModel(new javax.swing.table.DefaultTableModel(
	            new Object [][] {
	                {null, null, null, null},
	                {null, null, null, null},
	                {null, null, null, null},
	                {null, null, null, null}
	            },
	            new String [] {
	                "Title 1", "Title 2", "Title 3", "Title 4"
	            }
	        ));
	        jTable2.setName("jTable2"); // NOI18N
	        jScrollPane2.setViewportView(jTable2);

	        jTabbedPane1.addTab("Grade", jScrollPane2);

	        jScrollPane1.setName("jScrollPane1"); // NOI18N

	        jTable1.setModel(new javax.swing.table.DefaultTableModel(
	            new Object [][] {
	                {null, null, null, null},
	                {null, null, null, null},
	                {null, null, null, null},
	                {null, null, null, null}
	            },
	            new String [] {
	                "Title 1", "Title 2", "Title 3", "Title 4"
	            }
	        ));
	        jTable1.setName("jTable1"); // NOI18N
	        jScrollPane1.setViewportView(jTable1);

	        jTabbedPane1.addTab("Disciplinas", jScrollPane1);

	        jButton1.setText("adicionar");
	        jButton1.setName("jButton1"); // NOI18N

	        jButton2.setText("Finalizar Cadastro");
	        jButton2.setName("jButton2"); // NOI18N

	        jButton3.setText("Cancelar");
	        jButton3.setName("jButton3"); // NOI18N

	        jLabel3.setFont(new java.awt.Font("Dialog", 1, 9));
	        jLabel3.setText("* Campo Obrigatorio");
	        jLabel3.setName("jLabel3"); // NOI18N

	        jLabel4.setFont(new java.awt.Font("Dialog", 1, 9));
	        jLabel4.setText("* Campo Obrigatorio");
	        jLabel4.setName("jLabel4"); // NOI18N

	        jTextField3.setName("jTextField3"); // NOI18N

	        jButton4.setText("Buscar");
	        jButton4.setName("jButton4"); // NOI18N

	        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
	        this.setLayout(layout);
	        layout.setHorizontalGroup(
	            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	            .addGroup(layout.createSequentialGroup()
	                .addContainerGap()
	                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	                    .addGroup(layout.createSequentialGroup()
	                        .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 501, Short.MAX_VALUE)
	                        .addContainerGap())
	                    .addGroup(layout.createSequentialGroup()
	                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	                            .addGroup(layout.createSequentialGroup()
	                                .addComponent(jLabel2)
	                                .addGap(18, 18, 18)
	                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	                                    .addComponent(jLabel4)
	                                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)))
	                            .addGroup(layout.createSequentialGroup()
	                                .addComponent(jLabel1)
	                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
	                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	                                    .addComponent(jLabel3)
	                                    .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 443, Short.MAX_VALUE))))
	                        .addContainerGap())
	                    .addGroup(layout.createSequentialGroup()
	                        .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 298, javax.swing.GroupLayout.PREFERRED_SIZE)
	                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
	                        .addComponent(jButton4)
	                        .addContainerGap())
	                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
	                        .addComponent(jButton3)
	                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 305, Short.MAX_VALUE)
	                        .addComponent(jButton1)
	                        .addContainerGap())))
	            .addComponent(jButton2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 525, Short.MAX_VALUE)
	        );
	        layout.setVerticalGroup(
	            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	            .addGroup(layout.createSequentialGroup()
	                .addComponent(jLabel3)
	                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
	                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
	                    .addComponent(jLabel1)
	                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
	                .addGap(2, 2, 2)
	                .addComponent(jLabel4)
	                .addGap(3, 3, 3)
	                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
	                    .addComponent(jLabel2)
	                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
	                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
	                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
	                    .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
	                    .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE))
	                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
	                .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 289, Short.MAX_VALUE)
	                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
	                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
	                    .addComponent(jButton1)
	                    .addComponent(jButton3))
	                .addGap(13, 13, 13)
	                .addComponent(jButton2))
	        );
	    }// </editor-fold>//GEN-END:initComponents


	    // Variables declaration - do not modify//GEN-BEGIN:variables
	    private javax.swing.JButton jButton1;
	    private javax.swing.JButton jButton2;
	    private javax.swing.JButton jButton3;
	    private javax.swing.JButton jButton4;
	    private javax.swing.JLabel jLabel1;
	    private javax.swing.JLabel jLabel2;
	    private javax.swing.JLabel jLabel3;
	    private javax.swing.JLabel jLabel4;
	    private javax.swing.JScrollPane jScrollPane1;
	    private javax.swing.JScrollPane jScrollPane2;
	    private javax.swing.JTabbedPane jTabbedPane1;
	    private javax.swing.JTable jTable1;
	    private javax.swing.JTable jTable2;
	    private javax.swing.JTextField jTextField1;
	    private javax.swing.JTextField jTextField2;
	    private javax.swing.JTextField jTextField3;
	    // End of variables declaration//GEN-END:variables

	    private Observavel docRegulamentado = new Observavel();
	    private Observavel docNome = new Observavel();
	    
	    public void execute() {
	        initComponents();
	         if (cc==null)
	                cc = new ConcretDecorator(this);
	          initObserver();
	          camposClasse.add("Codigo");
	          camposClasse.add("Disciplina");
	          camposClasse.add("Requisito");
	          camposClasse.add("Periodo");
	          tabModel = new TabelaModelo(campos, tamanho, jTable1);
	          tabModelGrade = new TabelaModelo(camposClasse, tamanho, jTable2);
	          ListSelectionModel listModel = jTable1.getSelectionModel();
	          listModel.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
	          listModel.addListSelectionListener(list);
	          
	          ListSelectionModel listModelGrade = jTable2.getSelectionModel();
	          listModelGrade.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
	          listModelGrade.addListSelectionListener(listGrade);
	          jbtn1Listener();
	          setCurso();
	          finalizar();
	         // atualizaClasse();
	          grade();
	          atualiza();
	          cc.setVisible(true);
	    }
	     public void initObserver(){
	        Observer val = new ValidaEspecial();
	          docRegulamentado.setDocument(jTextField2.getDocument());
	         // docNome.setDocument(jTextField1.getDocument());

	          //docRegulamentado.addObserver(val)
	          docNome.addObserver(val);

	          jTextField1.getDocument().addDocumentListener(listener);
	       //   jTextField2.getDocument().addDocumentListener(listener);
	     }
	        public void setTNome(Observavel observavel){
	        observavel.setDocument(jTextField1.getDocument());
	        observavel.setChanged();
	        observavel.notifyObservers();
	        jTextField1.setDocument(observavel.getDocument());
	    }
	        public void setRegulamentado(Observavel observavel){
	        observavel.setDocument(jTextField2.getDocument());
	        observavel.setChanged();
	        observavel.notifyObservers();
	        jTextField2.setDocument(observavel.getDocument());
	    }
	  public void getEventDocument(Document doc){
	        if(doc.equals(docRegulamentado.getDocument()))
	                setRegulamentado(docRegulamentado);
	        else if(doc.equals(docNome.getDocument()))
	                setTNome(docNome);
	  }
	  DocumentListener listener = new DocumentListener() {

	            public void insertUpdate(DocumentEvent e) {
	               getEventDocument(e.getDocument());
	            }

	            public void removeUpdate(DocumentEvent e) {
	                getEventDocument(e.getDocument());
	            }

	            public void changedUpdate(DocumentEvent e) {
	                 getEventDocument(e.getDocument());
	            }
	        };
	        public Disciplina getSelectedDisciplina(Long codigo){
	    		return  (Disciplina) ClientCommand.carregaObjeto("DisciplinaService", "codigo="+codigo, "");
	    	}
	        
	        public Classe getSelectedClasse(Long codigo){
	    		return  (Classe) ClientCommand.carregaObjeto("ClasseService", "disciplina="+codigo, "");
	    	}
	        
	        ListSelectionListener list = new ListSelectionListener() {
	    		
	    		@Override
	    		public void valueChanged(ListSelectionEvent e) {
	    			try{
	    				if(jTable1.getSelectedRow()>=0){
	    			 disciplina = getSelectedDisciplina(Long.parseLong(jTable1.getValueAt(jTable1.getSelectedRow(), 0).toString()));
	    				}
	    				}catch(ArrayIndexOutOfBoundsException ea){
	    				disciplina = null;
	    			}
	    		}
	    	};	
	    	 ListSelectionListener listGrade = new ListSelectionListener() {
	     		
	     		@Override
	     		public void valueChanged(ListSelectionEvent e) {
	     			try{
	     				if(jTable2.getSelectedRow()>=0){
	     			 classe = getSelectedClasse(Long.parseLong(jTable2.getValueAt(jTable2.getSelectedRow(), 0).toString()));
	     				}
	     				}catch(ArrayIndexOutOfBoundsException ea){
	     				classe = null;
	     			}
	     		}
	     	};	
	     	public void atualiza() {
	    		((DefaultTableModel) jTable1.getModel()).setNumRows(0);
	    		jTable1.updateUI();
	    		StringBuilder condicao = new StringBuilder("codigo not in(");
	    		if(classes.size()==0)
	    			condicao.append("0");
	    		else
	    		for(int i =0;i<classes.size();i++){
	    			if(i <= classes.size()-1&&i>0)
	    				condicao.append(","+classes.get(i).getDisicplina().getId());
	    			else
	    				condicao.append(classes.get(i).getDisicplina().getId());
	    		}
	    		condicao.append(")");
	    		extra = (List) ClientCommand.carregar("DisciplinaService",condicao.toString(), "");
	    		for (int i = 0; i < extra.size(); i++) {
	    				try {
	    					valores = new LinkedList<Object>();
	    					valores.add(extra.get(i).getId());
	    					valores.add(extra.get(i).getNome());
	    					if (extra.get(i).getRequisito().getId() == 0)
	    						valores.add("Nenhum");
	    					else {
	    						extra.get(i).setRequisito(
	    								(Disciplina) ClientCommand.carregaObjeto(
	    										"DisciplinaService", "codigo = "
	    												+ extra.get(i).getRequisito()
	    														.getId(), ""));
	    						valores.add(extra.get(i).getRequisito().getNome());
	    					}
	    					valores.add(extra.get(i).getCargaHoraria());
	    					tabModel.setValores(valores);
	    					valores.clear();
	    				} catch (IndexOutOfBoundsException e) {

	    				}
	    		}
	    	}

	    	
	    	public void addClasse(){
	    		classe = new Classe();
	    		setClasse(classe);
	    		classes.add(classe);
	    	}
	    	
	    	public void atualizaClasse() {
	    		((DefaultTableModel) jTable2.getModel()).setNumRows(0);
	    		jTable2.updateUI();
	    		// grades.add(grade);
	    		for (int i = 0; i < classes.size(); i++) {
	    			valoresClasse = new LinkedList<Object>();
	    			valoresClasse.add(classes.get(i).getDisicplina().getId());
	    			valoresClasse.add(classes.get(i).getDisicplina().getNome());
	    			if (classes.get(i).getDisicplina().getRequisito().getId() == 0)
	    				valoresClasse.add("Nenhum");
	    			else {
	    				classes.get(i).getDisicplina().setRequisito(
	    						(Disciplina) ClientCommand.carregaObjeto(
	    								"DisciplinaService", "codigo = "
	    										+ classes.get(i).getDisicplina()
	    												.getRequisito().getId(), ""));
	    				valoresClasse.add(classes.get(i).getDisicplina().getRequisito()
	    						.getNome());
	    			}
	    			// valoresGrade.add(grades.get(i).getDisciplina().getRequisito().getNome());
	    			valoresClasse.add(classes.get(i).getPeriodo());
	    			tabModelGrade.setValores(valoresClasse);
	    			valoresClasse.clear();
	    		}
	    	}
	    	
	    	public void grade() {
	    		((DefaultTableModel) jTable2.getModel()).setNumRows(0);
	    		jTable2.updateUI();
	    		// grades.add(grade);
	    		classes = (List) ClientCommand.carregar("ClasseService", "curso="+curso.getId(), "");
	    		for (int i = 0; i < classes.size(); i++) {
	    			valoresClasse = new LinkedList<Object>();
	    			valoresClasse.add(classes.get(i).getDisicplina().getId());
	    			valoresClasse.add(classes.get(i).getDisicplina().getNome());
	    			if (classes.get(i).getDisicplina().getRequisito().getId() == 0)
	    				valoresClasse.add("Nenhum");
	    			else {
	    				classes.get(i).getDisicplina().setRequisito(
	    						(Disciplina) ClientCommand.carregaObjeto(
	    								"DisciplinaService", "codigo = "
	    										+ classes.get(i).getDisicplina()
	    												.getRequisito().getId(), ""));
	    				valoresClasse.add(classes.get(i).getDisicplina().getRequisito()
	    						.getNome());
	    			}
	    			// valoresGrade.add(grades.get(i).getDisciplina().getRequisito().getNome());
	    			valoresClasse.add(classes.get(i).getPeriodo());
	    			tabModelGrade.setValores(valoresClasse);
	    			valoresClasse.clear();
	    		}
	    	}
	    	
	    	public void setFields(){
	    		DataFacade facade = null;
				facade = new DataFacade(jTextField2.getText());
	    		curso.setNome(jTextField1.getText());
	    		curso.setAnoRegulamentado(facade.getDate());
	    	}
	    	public void setClasse(Classe g){
	    		g.setDisicplina(disciplina);
	    		periodo = Integer.parseInt(JOptionPane.showInputDialog("informe o Peiodo desta disciplina neste curso"));
	    		g.setPeriodo(periodo);
	    	}
	    	public void setCurso(){
	    		DataFacade facade = new DataFacade();
	    		jTextField2.setText(facade.getString(curso.getAnoRegulamentado()));
	    		jTextField1.setText(curso.getNome());
	    	}
	    	
	    	public void jbtn1Listener(){
	    		jButton1.setActionCommand("add");
	    		jButton1.addActionListener(new ActionListener() {
					
					@Override
					public void actionPerformed(ActionEvent arg0) {
						addClasse();
						atualizaClasse();
						atualiza();
					}
				});    		
	    	}
	    	public void finalizar(){
				jButton2.setActionCommand("finalizar");
				jButton2.addActionListener(new ActionListener() {
					
					@Override
					public void actionPerformed(ActionEvent arg0) {
						setFields();
						ClientCommand.alterar("CursoService",curso);
						curso = (Curso)ClientCommand.carregaObjeto("CursoService"," nome ='"+curso.getNome()+"' ","");
						for(int i = 0; i < classes.size();i++ ){
							classes.get(i).setCurso(curso);
							if(classes.get(i).getDisicplina().getId()!=null)
								ClientCommand.deletar("ClasseService",classes.get(i));
						}
					}
				});
			}
	    	
	    	 public void limpaFields(){
	        	 jTextField1.setText("");
	        	 jTextField2.setText("");
	        	 jTextField3.setText("");
					((DefaultTableModel) jTable1.getModel()).setNumRows(0);
			    	jTable1.updateUI();
			    	((DefaultTableModel) jTable2.getModel()).setNumRows(0);
			    	jTable2.updateUI();
	        }

	        
	    	@Override
	    	public void menuExemplo(JMenuItem item) {
	    		// TODO Auto-generated method stub
	    		
	    	}

	    	@Override
	    	public void menuFechar(JMenuItem item) {
	    		cc.dispose();		
	    	}

	    	@Override
	    	public void menuLimpa(JMenuItem item) {
	    		limpaFields();		
	    	}

	    	@Override
	    	public void menuManual(JMenuItem item) {
	    		// TODO Auto-generated method stub		
	    	}

	    	@Override
	    	public void menuMementor(JMenuItem item) {
	    		// TODO Auto-generated method stub		
	    	}

	    	@Override
	    	public void menuOperacao(JMenuItem item) {
	    		item.setText("Atualizar Curso");
	    		finalizar();
	    		limpaFields();
	    	}

	    	@Override
	    	public void menuSobre(JMenuItem item) {
	    		// TODO Auto-generated method stub
	    		
	    	}
}
